package com.qst.order.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qst.order.domain.*;
import com.qst.order.domain.VO.ProcessRecordVO;
import com.qst.order.domain.VO.RefundDetailVO;
import com.qst.order.mapper.*;
import com.qst.order.service.ReturnApplyService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ReturnApplyServiceImpl extends ServiceImpl<ReturnApplyMapper, ReturnApply> implements ReturnApplyService {

    private final ReturnApplyItemMapper returnApplyItemMapper;
    private final OrderMapper orderMapper;
    private final ReturnApplyMapper returnApplyMapper;
    private final UserMapper userMapper;
    private final OrderItemMapper orderItemMapper;
    private final OrderPayMapper orderPayMapper;
    @Override
    public void saveItems(List<ReturnApplyItem> items) {

            // 批量插入明细数据
            returnApplyItemMapper.batchInsert(items);

    }

    @Override
    public List<ReturnApplyItem> queryItemsByReturnId(Integer returnId) {
        QueryWrapper<ReturnApplyItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("return_id", returnId);
        return returnApplyItemMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<ReturnApply> getRefundPage(
            int page, int size,
            String keyword, Integer status,
            String startDate, String endDate
    ) {
        IPage<ReturnApply> pagination =new Page<>(page,size);
        return returnApplyMapper.selectRefundPage(pagination, keyword, status, startDate, endDate);
    }

    @Override
    public RefundDetailVO getRefundDetail(Integer returnId) {
        // 1. 查询基本信息
        ReturnApply returnApply = returnApplyMapper.selectRefundById(returnId);
        if (returnApply == null) {
            return null;
        }
        // 2. 转换为VO对象
        RefundDetailVO detailVO = new RefundDetailVO();
        BeanUtils.copyProperties(returnApply, detailVO);

        // 3. 查询明细列表
        List<ReturnApplyItem> items = returnApplyItemMapper.selectItemsByReturnId(returnId);
        log.warn("items: {}", items);
        detailVO.setItems(items);

        // 4. 构建处理记录（实际项目中应从日志表查询）
        List<ProcessRecordVO> records = new ArrayList<>();

        // 初始记录：用户提交申请
        ProcessRecordVO submitRecord = new ProcessRecordVO();
        submitRecord.setProcessTime(returnApply.getCreateTime());
        submitRecord.setProcessResult("用户提交退货申请");
        submitRecord.setProcessNote("");
        records.add(submitRecord);

        // 处理记录：商家操作
        if (returnApply.getStatus() == 1) {
            ProcessRecordVO agreeRecord = new ProcessRecordVO();
            agreeRecord.setProcessTime(returnApply.getUpdateTime());
            agreeRecord.setProcessResult("商家同意退货");
            agreeRecord.setProcessNote("");
            records.add(agreeRecord);
        } else if (returnApply.getStatus() == 2) {
            ProcessRecordVO rejectRecord = new ProcessRecordVO();
            rejectRecord.setProcessTime(returnApply.getUpdateTime());
            rejectRecord.setProcessResult("商家拒绝退货");
            rejectRecord.setProcessNote(returnApply.getRejectReason());
            records.add(rejectRecord);
        }
        detailVO.setProcessRecords(records);
        return detailVO;
    }

    @Transactional
    @Override
    public ReturnApply agreeRefund(Integer returnId) {
        // 1. 查询退货申请
        ReturnApply returnApply = returnApplyMapper.selectById(returnId);
        if (returnApply == null) {
            throw new RuntimeException("退货申请不存在");
        }
        if (returnApply.getStatus() != 0) {
            throw new RuntimeException("该申请已处理，无法重复操作");
        }
        // 2. 更新退货申请状态
        returnApply.setStatus(1); // 已同意
        returnApply.setUpdateTime(LocalDateTime.now());
        returnApplyMapper.updateById(returnApply);

        // 3. 更新订单状态为"退货退款"
        orderMapper.updateOrderStatus(//包含退货时间设置
                returnApply.getOrderId(),
                "refunded"
        );
        // 4. 更新订单项状态为"退货中"
        List<ReturnApplyItem> returnApplyItems = returnApplyItemMapper.selectItemsByReturnId(returnId);
        if (CollectionUtils.isEmpty(returnApplyItems)) {
            throw new RuntimeException("退货申请未关联任何商品，无法处理");
        }
        // 3. 提取订单项ID列表（用于后续更新订单项状态）
        List<String> orderItemNo = returnApplyItems.stream()
                .map(ReturnApplyItem::getItemNo) //
                .toList();

        try {

            //  批量更新订单项状态为“已退款”
            orderItemMapper.batchUpdateStatus(orderItemNo, "refunded"); // 订单项状态：已退款
            //计算退款金额
            BigDecimal refundAmount = returnApplyItemMapper.selectRefundAmount(returnId);
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getUsername, returnApply.getUsername())
                    // 改用setSql，将SQL计算逻辑作为片段拼接
                    .setSql("money = COALESCE(money, 0) + " + refundAmount);
            userMapper.update(updateWrapper);
            // 4. 插入退款记录
            OrderPay orderPay = new OrderPay();
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", returnApply.getUsername()));
            orderPay.setUserId(user.getId());
            orderPay.setMoney(user.getMoney().subtract(refundAmount));
            orderPay.setOrderNo(returnApply.getOrderNo());
            orderPay.setPayType("退款到账");
            orderPay.setPayMoney(refundAmount);
            orderPay.setPayTime(LocalDateTime.now());
            orderPayMapper.insert(orderPay);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return returnApply;
    }

    @Transactional
    @Override
    public ReturnApply rejectRefund(Integer returnId, String reason) {
        // 1. 查询退货申请
        ReturnApply returnApply = returnApplyMapper.selectById(returnId);
        if (returnApply == null) {
            throw new RuntimeException("退货申请不存在");
        }
        if (returnApply.getStatus() != 0) {
            throw new RuntimeException("该申请已处理，无法重复操作");
        }

        // 2. 更新退货申请状态
        returnApply.setStatus(2); // 已拒绝
        returnApply.setUpdateTime(LocalDateTime.now());
        returnApply.setRejectReason(reason); // 保存拒绝理由
        returnApplyMapper.updateById(returnApply);

        // 3. 更新订单状态为"退款被拒绝"
        orderMapper.updateOrderStatus(
                returnApply.getOrderId(),
                "refund_rejected"
        );
        //查询退货订单项
//        LambdaQueryWrapper<ReturnApplyItem> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ReturnApplyItem::getReturnId, returnId);
//        List<ReturnApplyItem> returnApplyItems = returnApplyItemMapper.selectList(queryWrapper);
//        returnApplyItems.forEach(returnApplyItem -> {
//            OrderItem orderItem = orderItemMapper.selectOne(new QueryWrapper<OrderItem>().eq("item_no", returnApplyItem.getItemNo()
//                    ).eq("order_id", returnApply.getOrderId()));
//            log.warn("orderItem: {}", orderItem);
//            orderItem.setItemStatus("refund_rejected");
//            orderItemMapper.update(orderItem,null);
//        });

        return returnApply;
    }
}
